package servlet;

import entity.Emp;
import util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

//@WebServlet("/emp/*")
@WebServlet("*.emp")
public class EmpServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        String path = req.getServletPath();
//        System.out.println("path:" + path);
//        out.println("<h1>我进来了</h1>");

        switch (path) {
            case "/findAll.emp":
                findAll(req, resp);
                break;
            case "/add.emp":
                addEmp(req, resp);
                break;
            case "/findById.emp":
                findById(req, resp);
                break;
            case "/modify.emp":
                modifyEmp(req, resp);
                break;
            case "/delete.emp":
                deleteEmp(req, resp);
                break;
            default:
                out.println("<h1 style='color:red;'>您访问的资源不存在,请重新访问</h1>");
                break;
        }

    }

    public void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        System.out.println("执行查询所有操作");
        // 进入数据库查询所有员工,封装成员工集合
        // 通过请求将员工集合传递到jsp页面中
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Emp> emps = new ArrayList<>();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8", "root", "root");
            String sql = new StringBuffer()
                    .append(" select id,name,salary ")
                    .append(" from t_emp")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                Emp emp = new Emp();
                emp.setId(rs.getInt("id"));
                emp.setName(rs.getString("name"));
                emp.setSalary(rs.getDouble("salary"));
                emps.add(emp);
            }
            req.setAttribute("emps", emps);
            req.getRequestDispatcher("/ems/empList.jsp").forward(req,resp);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void addEmp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        // 处理Post请求乱码
        req.setCharacterEncoding("utf-8");
        String name = req.getParameter("name");
        String salary = req.getParameter("salary");
        String gender = req.getParameter("gender");
        String edu = req.getParameter("edu");
        String[] hobbies = req.getParameterValues("hobbies");
        // JDBC操作
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8", "root", "root");
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_emp ")
                    .append("   (name,salary,gender,edu,hobbies)")
                    .append(" values ")
                    .append("  (?,?,?,?,?)")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, name);
            ps.setDouble(2, Double.parseDouble(salary));
            ps.setString(3, gender);
            ps.setString(4, edu);
            ps.setString(5, StringUtil.arrayToString(hobbies));
            ps.executeUpdate();

            resp.sendRedirect(req.getContextPath() + "/findAll.emp");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            // 向请求中存储了一条数据,数据的key为msg,value为未找到数据库驱动
            // 只要是同一个请求,都可以根据key获取到value
            req.setAttribute("msg", "未找到数据库驱动");
            // 根据key获取对应的value
//            req.getAttribute("msg");
            req.getRequestDispatcher("/ems/addEmp.jsp").forward(req, resp);
        } catch (SQLException e) {
            e.printStackTrace();
            req.setAttribute("msg", "数据访问异常");
            req.getRequestDispatcher("/ems/addEmp.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("msg", "服务器内部异常");
            req.getRequestDispatcher("/ems/addEmp.jsp").forward(req, resp);
        }
    }

    public void findById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Emp emp = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8", "root", "root");
            String sql = new StringBuffer()
                    .append(" select id,name,salary,gender,edu,hobbies ")
                    .append(" from t_emp ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1,Integer.parseInt(id));
            rs = ps.executeQuery();
            if (rs.next()){
                emp = new Emp();
                emp.setId(rs.getInt("id"));
                emp.setName(rs.getString("name"));
                emp.setSalary(rs.getDouble("salary"));
                emp.setGender(rs.getString("gender"));
                emp.setEdu(rs.getString("edu"));
                emp.setHob(rs.getString("hobbies"));
            }
            req.setAttribute("emp",emp);
            req.getRequestDispatcher("/ems/modifyEmp.jsp").forward(req,resp);
        } catch (SQLException e) {
            req.setAttribute("msg","数据访问异常");
        } catch (ClassNotFoundException e) {
            req.setAttribute("msg","未找到驱动");
        }
    }

    public void modifyEmp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String salary = req.getParameter("salary");
        String gender = req.getParameter("gender");
        String edu = req.getParameter("edu");
        String[] hobbies = req.getParameterValues("hobbies");

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8","root","root");
            String sql = new StringBuffer()
                    .append(" update t_emp ")
                    .append(" set ")
                    .append("   name = ?,")
                    .append("   salary = ?,")
                    .append("   gender = ?,")
                    .append("   edu = ?,")
                    .append("   hobbies = ?")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,name);
            ps.setDouble(2,Double.parseDouble(salary));
            ps.setString(3,gender);
            ps.setString(4,edu);
            ps.setString(5, StringUtil.arrayToString(hobbies));
            ps.setInt(6,Integer.parseInt(id));
            ps.executeUpdate();
            resp.sendRedirect(req.getContextPath()+"/findAll.emp");
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public void deleteEmp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8","root","root");
            String sql = new StringBuffer()
                    .append(" delete from t_emp ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1,Integer.parseInt(id));
            ps.executeUpdate();
            resp.sendRedirect(req.getContextPath()+"/findAll.emp");
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
